package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.example.demo.common.redis.CacheTime;
import com.example.demo.domain.Announce;
import com.example.demo.service.AnnounceService;
import com.example.demo.utils.BooleanTF;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/announce")
public class AnnounceController {

    @Autowired
    private AnnounceService announceService;

    @Autowired
    private RedisTemplate redisTemplate;

    //添加记录
    @PostMapping("/insert")
    public boolean insertSelective(@RequestBody Announce body) {
        //插入到MySQL数据库
        int res = announceService.insertSelective(body);

        //插入到Redis缓存
        redisTemplate.opsForValue().set("announce", JSON.toJSON(announceService.selectAll()).toString(), CacheTime.CACHE_EXP_FOREVER);

        return BooleanTF.judge(res);//调用自定义工具类的方法，判断是否插入成功
    }

    //获取redis缓存中的announce数据
    @GetMapping("byRedis")
    public JSONArray getDateByRedis() {
        String str = (String) redisTemplate.opsForValue().get("announce");
        JSONArray jsonArray = JSON.parseArray(str);
        return jsonArray;
    }

    //删除，使信息不显示
    @DeleteMapping("/delete/{id}")
    public boolean updateByIsStatus(@PathVariable("id") Integer announceId) {
        int res = announceService.updateByIsStatus(announceId);
        return BooleanTF.judge(res);
    }

    //修改信息
    @PutMapping("/update")
    public boolean updateByPrimaryKeySelective(@RequestBody Announce record) {
        int res = announceService.updateByPrimaryKeySelective(record);
        return BooleanTF.judge(res);
    }

    //查询所有信息
    @GetMapping("/selectAll")
    public List<Announce> selectAll() {
        return announceService.selectAll();
    }

    //按发布信息的ID进行查询
    @GetMapping("/selectById/{id}")
    public Announce selectByPrimaryKey(@PathVariable("id") Integer announceId) {
        return announceService.selectByPrimaryKey(announceId);
    }

    //按发布类型查询
    @GetMapping("/selectByType/{type}")
    public List<Announce> selectByAnnounceType(@PathVariable("type") boolean announceType) {
        return announceService.selectByAnnounceType(announceType);
    }

    //按物品名称模糊查询
    @GetMapping("/selectByItemName")
    public List<Announce> selectByItemName(@RequestParam("itemName") String itemName) {
        return announceService.selectByItemName(itemName);
    }
}
